<!DOCTYPE HTML>
<html lang="en-US" >
    
    <head>
        
        <meta charset="UTF-8">
        <title>动态创建控制器(了解) | 微博项目的简介</title>
        <meta content="text/html; charset=utf-8" http-equiv="Content-Type">
        <meta name="description" content="">
        <meta name="generator" content="GitBook 1.0.3">
        <meta name="HandheldFriendly" content="true"/>
        <meta name="viewport" content="width=device-width, initial-scale=1, user-scalable=no">
        <meta name="apple-mobile-web-app-capable" content="yes">
        <meta name="apple-mobile-web-app-status-bar-style" content="black">
        <link rel="apple-touch-icon-precomposed" sizes="152x152" href="../gitbook/images/apple-touch-icon-precomposed-152.png">
        <link rel="shortcut icon" href="../gitbook/images/favicon.ico" type="image/x-icon">
        
    
    
    
    <link rel="next" href="../5storyboard_reference/README.html" />
    
    
    <link rel="prev" href="../03/README.html" />
    

        
    </head>
    <body>
        
        
<link rel="stylesheet" href="../gitbook/style.css">


        
    <div class="book"  data-level="4" data-basepath=".." data-revision="1457654214927">
    

<div class="book-summary">
    <div class="book-search">
        <input type="text" placeholder="Type to search" class="form-control" />
    </div>
    <ul class="summary">
        
    	
    	
    	

        

        
    
        
        <li class="chapter " data-level="0" data-path="index.html">
            
                
                    <a href="../index.html">
                        <i class="fa fa-check"></i>
                        
                         微博项目的简介
                    </a>
                
            
            
        </li>
    
        
        <li class="chapter " data-level="1" data-path="01/README.html">
            
                
                    <a href="../01/README.html">
                        <i class="fa fa-check"></i>
                        
                            <b>1.</b>
                        
                         项目部署
                    </a>
                
            
            
        </li>
    
        
        <li class="chapter " data-level="2" data-path="02/README.html">
            
                
                    <a href="../02/README.html">
                        <i class="fa fa-check"></i>
                        
                            <b>2.</b>
                        
                         初始化项目
                    </a>
                
            
            
        </li>
    
        
        <li class="chapter " data-level="3" data-path="03/README.html">
            
                
                    <a href="../03/README.html">
                        <i class="fa fa-check"></i>
                        
                            <b>3.</b>
                        
                         纯代码搭建项目框架
                    </a>
                
            
            
        </li>
    
        
        <li class="chapter active" data-level="4" data-path="4json/README.html">
            
                
                    <a href="../4json/README.html">
                        <i class="fa fa-check"></i>
                        
                            <b>4.</b>
                        
                         动态创建控制器(了解)
                    </a>
                
            
            
        </li>
    
        
        <li class="chapter " data-level="5" data-path="5storyboard_reference/README.html">
            
                
                    <a href="../5storyboard_reference/README.html">
                        <i class="fa fa-check"></i>
                        
                            <b>5.</b>
                        
                         StoryBoard Reference
                    </a>
                
            
            
        </li>
    
        
        <li class="chapter " data-level="6" data-path="6tabbar/README.html">
            
                
                    <a href="../6tabbar/README.html">
                        <i class="fa fa-check"></i>
                        
                            <b>6.</b>
                        
                         布局TabBar
                    </a>
                
            
            
        </li>
    
        
        <li class="chapter " data-level="7" data-path="7/README.html">
            
                
                    <a href="../7/README.html">
                        <i class="fa fa-check"></i>
                        
                            <b>7.</b>
                        
                         访客视图
                    </a>
                
            
            
        </li>
    


        
        <li class="divider"></li>
        <li>
            <a href="http://www.gitbook.io/" target="blank" class="gitbook-link">Published using GitBook</a>
        </li>
        
    </ul>
</div>

    <div class="book-body">
        <div class="body-inner">
            <div class="book-header">
    <!-- Actions Left -->
    <a href="#" class="btn pull-left toggle-summary" aria-label="Toggle summary"><i class="fa fa-align-justify"></i></a>
    <a href="#" class="btn pull-left toggle-search" aria-label="Toggle search"><i class="fa fa-search"></i></a>
    
    <div id="font-settings-wrapper" class="dropdown pull-left">
        <a href="#" class="btn toggle-dropdown" aria-label="Toggle font settings"><i class="fa fa-font"></i>
        </a>
        <div class="dropdown-menu font-settings">
    <div class="dropdown-caret">
        <span class="caret-outer"></span>
        <span class="caret-inner"></span>
    </div>

    <div class="buttons">
        <button type="button" id="reduce-font-size" class="button size-2">A</button>
        <button type="button" id="enlarge-font-size" class="button size-2">A</button>
    </div>

    <div class="buttons font-family-list">
        <button type="button" data-font="0" class="button">Serif</button>
        <button type="button" data-font="1" class="button">Sans</button>
    </div>

    <div class="buttons color-theme-list">
        <button type="button" id="color-theme-preview-0" class="button size-3" data-theme="0">White</button>
        <button type="button" id="color-theme-preview-1" class="button size-3" data-theme="1">Sepia</button>
        <button type="button" id="color-theme-preview-2" class="button size-3" data-theme="2">Night</button>
    </div>
</div>

    </div>

    <!-- Actions Right -->
    
    <div class="dropdown pull-right">
        <a href="#" class="btn toggle-dropdown" aria-label="Toggle share dropdown"><i class="fa fa-share-alt"></i>
        </a>
        <div class="dropdown-menu font-settings dropdown-left">
            <div class="dropdown-caret">
                <span class="caret-outer"></span>
                <span class="caret-inner"></span>
            </div>
            <div class="buttons">
                <button type="button" data-sharing="twitter" class="button">Twitter</button>
                <button type="button" data-sharing="google-plus" class="button">Google</button>
                <button type="button" data-sharing="facebook" class="button">Facebook</button>
                <button type="button" data-sharing="weibo" class="button">Weibo</button>
                <button type="button" data-sharing="instapaper" class="button">Instapaper</button>
            </div>
        </div>
    </div>
    

    
    <a href="#" target="_blank" class="btn pull-right google-plus-sharing-link sharing-link" data-sharing="google-plus" aria-label="Share on Google Plus"><i class="fa fa-google-plus"></i></a>
    
    
    <a href="#" target="_blank" class="btn pull-right facebook-sharing-link sharing-link" data-sharing="facebook" aria-label="Share on Facebook"><i class="fa fa-facebook"></i></a>
    
    
    <a href="#" target="_blank" class="btn pull-right twitter-sharing-link sharing-link" data-sharing="twitter" aria-label="Share on Twitter"><i class="fa fa-twitter"></i></a>
    
    

    <!-- Title -->
    <h1>
        <i class="fa fa-circle-o-notch fa-spin"></i>
        <a href="../" >微博项目的简介</a>
    </h1>
</div>

            <div class="page-wrapper" tabindex="-1">
                <div class="page-inner">
                
                
                    <section class="normal" id="section-gitbook_14">
                    
                        <h1 id="json">通过json动态创建控制器(了解)</h1>
<h3 id="">通过字符串来创建控制器</h3>
<ul>
<li>如果通过字符串来创建控制器<ul>
<li>不可以直接通过类型来获取对应的类</li>
<li>因为Swift有命名空间,类前需要加上命名空间的名称</li>
</ul>
</li>
<li>获取命名空间的名称</li>
</ul>
<pre><code class="lang-swift"><span class="hljs-keyword">let</span> executable = <span class="hljs-type">NSBundle</span>.mainBundle().infoDictionary![<span class="hljs-string">"CFBundleExecutable"</span>] <span class="hljs-keyword">as</span>? <span class="hljs-type">String</span>
</code></pre>
<ul>
<li>通过字符串创建对象<ul>
<li>获取类的名称</li>
<li>获取类的真实类型</li>
<li>创建对应类的对象</li>
</ul>
</li>
</ul>
<pre><code class="lang-swift">    <span class="hljs-comment">// 1.获取对应的类</span>
    guard <span class="hljs-keyword">let</span> childVcClass : <span class="hljs-type">AnyClass</span> = <span class="hljs-type">NSClassFromString</span>(executable + <span class="hljs-string">"."</span> + childCVcName) <span class="hljs-keyword">else</span> {
        <span class="hljs-type">XMGLog</span>(<span class="hljs-string">"转成对应的类失败"</span>)
        <span class="hljs-keyword">return</span>
    }

    <span class="hljs-comment">// 2.拿到对应的类</span>
    <span class="hljs-keyword">let</span> childClass = childVcClass <span class="hljs-keyword">as</span>! <span class="hljs-type">UITableViewController</span>.<span class="hljs-type">Type</span>
    <span class="hljs-keyword">let</span> childVc = childClass.<span class="hljs-keyword">init</span>()
</code></pre>
<ul>
<li>完整代码</li>
</ul>
<pre><code class="lang-swift">    <span class="hljs-keyword">override</span> <span class="hljs-func"><span class="hljs-keyword">func</span> <span class="hljs-title">viewDidLoad</span><span class="hljs-params">()</span> </span>{
        <span class="hljs-keyword">super</span>.viewDidLoad()

        <span class="hljs-comment">// 添加自控制器</span>
        <span class="hljs-keyword">self</span>.addChildViewController(<span class="hljs-string">"HomeViewController"</span>, imageName: <span class="hljs-string">"tabbar_home"</span>, title: <span class="hljs-string">"主页"</span>)
        <span class="hljs-keyword">self</span>.addChildViewController(<span class="hljs-string">"MessageViewController"</span>, imageName: <span class="hljs-string">"tabbar_message_center"</span>, title: <span class="hljs-string">"消息"</span>)
        <span class="hljs-keyword">self</span>.addChildViewController(<span class="hljs-string">"DiscoverViewController"</span>, imageName: <span class="hljs-string">"tabbar_discover"</span>, title: <span class="hljs-string">"广场"</span>)
        <span class="hljs-keyword">self</span>.addChildViewController(<span class="hljs-string">"ProfileViewController"</span>, imageName: <span class="hljs-string">"tabbar_profile"</span>, title: <span class="hljs-string">"我"</span>)
    }

    private <span class="hljs-func"><span class="hljs-keyword">func</span> <span class="hljs-title">addChildViewController</span><span class="hljs-params">(childCVcName: String, imageName : String, title : String)</span> </span>{

        <span class="hljs-comment">// 0.获取命名空间</span>
        guard <span class="hljs-keyword">let</span> executable = <span class="hljs-type">NSBundle</span>.mainBundle().infoDictionary![<span class="hljs-string">"CFBundleExecutable"</span>] <span class="hljs-keyword">as</span>? <span class="hljs-type">String</span> <span class="hljs-keyword">else</span> {
            <span class="hljs-type">XMGLog</span>(<span class="hljs-string">"没有命名空间"</span>)
            <span class="hljs-keyword">return</span>
        }

        <span class="hljs-comment">// 1.获取对应的类</span>
        guard <span class="hljs-keyword">let</span> childVcClass : <span class="hljs-type">AnyClass</span> = <span class="hljs-type">NSClassFromString</span>(executable + <span class="hljs-string">"."</span> + childCVcName) <span class="hljs-keyword">else</span> {
            <span class="hljs-type">XMGLog</span>(<span class="hljs-string">"转成对应的类失败"</span>)
            <span class="hljs-keyword">return</span>
        }

        <span class="hljs-comment">// 2.拿到对应的类</span>
        <span class="hljs-keyword">let</span> childClass = childVcClass <span class="hljs-keyword">as</span>! <span class="hljs-type">UITableViewController</span>.<span class="hljs-type">Type</span>
        <span class="hljs-keyword">let</span> childVc = childClass.<span class="hljs-keyword">init</span>()

        <span class="hljs-comment">// 3.创建自控制器</span>
        <span class="hljs-keyword">let</span> homeNav = <span class="hljs-type">UINavigationController</span>(rootViewController: childVc)

        <span class="hljs-comment">// 4.设置标题</span>
        childVc.title = title
        childVc.tabBarItem.selectedImage = <span class="hljs-type">UIImage</span>(named: imageName + <span class="hljs-string">"_highlighted"</span>)
        childVc.tabBarItem.image = <span class="hljs-type">UIImage</span>(named: imageName)

        <span class="hljs-comment">// 5.添加到UITabbarController</span>
        <span class="hljs-keyword">self</span>.addChildViewController(homeNav)
    }
}
</code></pre>
<h3 id="json">读取json文件.创建对应的控制器</h3>
<ul>
<li>读取json文件<ul>
<li>从服务器获取json文件(本地)</li>
<li>加载对应的json文件</li>
<li>通过序列化转成对应的类型</li>
</ul>
</li>
</ul>
<pre><code class="lang-swift">       <span class="hljs-comment">// 1.1.获取路径</span>
    <span class="hljs-keyword">let</span> path = <span class="hljs-type">NSBundle</span>.mainBundle().pathForResource(<span class="hljs-string">"MainVCSettings.json"</span>, ofType: <span class="hljs-built_in">nil</span>)
    <span class="hljs-comment">// 1.2.加载数据</span>
    guard <span class="hljs-keyword">let</span> data = <span class="hljs-type">NSData</span>(contentsOfFile: path!) <span class="hljs-keyword">else</span> {
        <span class="hljs-type">XMGLog</span>(<span class="hljs-string">"没有获取到json数据"</span>)
        addChildViewController()
        <span class="hljs-keyword">return</span>
    }

    <span class="hljs-comment">// 1.3.通过序列化获取内容</span>
    guard <span class="hljs-keyword">let</span> childVcArray = try? <span class="hljs-type">NSJSONSerialization</span>.<span class="hljs-type">JSONObjectWithData</span>(data, options: <span class="hljs-type">NSJSONReadingOptions</span>.<span class="hljs-type">MutableContainers</span>) <span class="hljs-keyword">as</span>! [[<span class="hljs-type">String</span> : <span class="hljs-type">AnyObject</span>]] <span class="hljs-keyword">else</span> {
        <span class="hljs-built_in">print</span>(<span class="hljs-string">"没有获取到值"</span>)
        addChildViewController()
        <span class="hljs-keyword">return</span>
    }
</code></pre>
<ul>
<li>注意:<code>JSONObjectWithData(data: NSData, options opt: NSJSONReadingOptions)</code>函数会抛出异常<ul>
<li>如果发现在调用一个方法时,会出现throws.则需要处理异常</li>
<li>处理异常三种方式<ul>
<li>try方式</li>
<li>try?方式</li>
<li>try!方式</li>
</ul>
</li>
</ul>
</li>
</ul>
<pre><code class="lang-swift">    处理异常三种方式
    <span class="hljs-number">1</span>.try方式
    <span class="hljs-keyword">do</span> {
    <span class="hljs-keyword">let</span> childVcArray = try <span class="hljs-type">NSJSONSerialization</span>.<span class="hljs-type">JSONObjectWithData</span>(data, options: <span class="hljs-type">NSJSONReadingOptions</span>.<span class="hljs-type">MutableContainers</span>)
    } catch {
    <span class="hljs-comment">// 如果有错误,则错误会放到一个变量:error中</span>
    <span class="hljs-type">XMGLog</span>(error)
    }
    <span class="hljs-number">2</span>.try?方式
    如果有值,则返回对应的值.如果没有值,则返回<span class="hljs-built_in">nil</span>.
    也就是:返回的类型时一个可选类型
    <span class="hljs-number">3</span>.try!方式:不建议使用
    相当于告诉系统一定没有异常,该方式非常危险.很容易崩溃
</code></pre>
<ul>
<li>完整代码</li>
</ul>
<pre><code class="lang-swift">    <span class="hljs-keyword">override</span> <span class="hljs-func"><span class="hljs-keyword">func</span> <span class="hljs-title">viewDidLoad</span><span class="hljs-params">()</span> </span>{
        <span class="hljs-keyword">super</span>.viewDidLoad()

        <span class="hljs-comment">// 1.加载json中的数据</span>
        <span class="hljs-comment">// 1.1.获取路径</span>
        <span class="hljs-keyword">let</span> path = <span class="hljs-type">NSBundle</span>.mainBundle().pathForResource(<span class="hljs-string">"MainVCSettings.json"</span>, ofType: <span class="hljs-built_in">nil</span>)
        <span class="hljs-comment">// 1.2.加载数据</span>
        guard <span class="hljs-keyword">let</span> data = <span class="hljs-type">NSData</span>(contentsOfFile: path!) <span class="hljs-keyword">else</span> {
            <span class="hljs-type">XMGLog</span>(<span class="hljs-string">"没有获取到json数据"</span>)
            addChildViewController()
            <span class="hljs-keyword">return</span>
        }

        <span class="hljs-comment">// 1.3.通过序列化获取内容</span>
        guard <span class="hljs-keyword">let</span> childVcArray = try? <span class="hljs-type">NSJSONSerialization</span>.<span class="hljs-type">JSONObjectWithData</span>(data, options: <span class="hljs-type">NSJSONReadingOptions</span>.<span class="hljs-type">MutableContainers</span>) <span class="hljs-keyword">as</span>! [[<span class="hljs-type">String</span> : <span class="hljs-type">AnyObject</span>]] <span class="hljs-keyword">else</span> {
            <span class="hljs-built_in">print</span>(<span class="hljs-string">"没有获取到值"</span>)
            addChildViewController()
            <span class="hljs-keyword">return</span>
        }

        <span class="hljs-comment">// 1.4.遍历数组,并且创建控制器</span>
        <span class="hljs-keyword">for</span> dict <span class="hljs-keyword">in</span> childVcArray {
            <span class="hljs-comment">// 1.取出类名称</span>
            <span class="hljs-keyword">let</span> vcName = dict[<span class="hljs-string">"vcName"</span>] <span class="hljs-keyword">as</span>! <span class="hljs-type">String</span>

            <span class="hljs-comment">// 2.取出标题</span>
            <span class="hljs-keyword">let</span> title = dict[<span class="hljs-string">"title"</span>] <span class="hljs-keyword">as</span>! <span class="hljs-type">String</span>

            <span class="hljs-comment">// 3.取出图标名称</span>
            <span class="hljs-keyword">let</span> imageName = dict[<span class="hljs-string">"imageName"</span>] <span class="hljs-keyword">as</span>! <span class="hljs-type">String</span>

            <span class="hljs-comment">// 4.创建控制器</span>
            addChildViewController(vcName, imageName: imageName, title: title)
        }
    }

    private <span class="hljs-func"><span class="hljs-keyword">func</span> <span class="hljs-title">addChildViewController</span><span class="hljs-params">()</span> </span>{
        <span class="hljs-keyword">self</span>.addChildViewController(<span class="hljs-string">"HomeViewController"</span>, imageName: <span class="hljs-string">"tabbar_home"</span>, title: <span class="hljs-string">"主页"</span>)
        <span class="hljs-keyword">self</span>.addChildViewController(<span class="hljs-string">"MessageViewController"</span>, imageName: <span class="hljs-string">"tabbar_message_center"</span>, title: <span class="hljs-string">"消息"</span>)
        <span class="hljs-keyword">self</span>.addChildViewController(<span class="hljs-string">"DiscoverViewController"</span>, imageName: <span class="hljs-string">"tabbar_discover"</span>, title: <span class="hljs-string">"广场"</span>)
        <span class="hljs-keyword">self</span>.addChildViewController(<span class="hljs-string">"ProfileViewController"</span>, imageName: <span class="hljs-string">"tabbar_profile"</span>, title: <span class="hljs-string">"我"</span>)
    }

    private <span class="hljs-func"><span class="hljs-keyword">func</span> <span class="hljs-title">addChildViewController</span><span class="hljs-params">(childCVcName: String, imageName : String, title : String)</span> </span>{

        <span class="hljs-comment">// 0.获取命名空间</span>
        guard <span class="hljs-keyword">let</span> executable = <span class="hljs-type">NSBundle</span>.mainBundle().infoDictionary![<span class="hljs-string">"CFBundleExecutable"</span>] <span class="hljs-keyword">as</span>? <span class="hljs-type">String</span> <span class="hljs-keyword">else</span> {
            <span class="hljs-type">XMGLog</span>(<span class="hljs-string">"没有命名空间"</span>)
            <span class="hljs-keyword">return</span>
        }

        <span class="hljs-comment">// 1.获取对应的类</span>
        guard <span class="hljs-keyword">let</span> childVcClass : <span class="hljs-type">AnyClass</span> = <span class="hljs-type">NSClassFromString</span>(executable + <span class="hljs-string">"."</span> + childCVcName) <span class="hljs-keyword">else</span> {
            <span class="hljs-type">XMGLog</span>(<span class="hljs-string">"转成对应的类失败"</span>)
            <span class="hljs-keyword">return</span>
        }

        <span class="hljs-comment">// 2.拿到对应的类</span>
        <span class="hljs-keyword">let</span> childClass = childVcClass <span class="hljs-keyword">as</span>! <span class="hljs-type">UITableViewController</span>.<span class="hljs-type">Type</span>
        <span class="hljs-keyword">let</span> childVc = childClass.<span class="hljs-keyword">init</span>()

        <span class="hljs-comment">// 3.创建自控制器</span>
        <span class="hljs-keyword">let</span> homeNav = <span class="hljs-type">UINavigationController</span>(rootViewController: childVc)

        <span class="hljs-comment">// 4.设置标题</span>
        childVc.title = title
        childVc.tabBarItem.selectedImage = <span class="hljs-type">UIImage</span>(named: imageName + <span class="hljs-string">"_highlighted"</span>)
        childVc.tabBarItem.image = <span class="hljs-type">UIImage</span>(named: imageName)

        <span class="hljs-comment">// 5.添加到UITabbarController</span>
        <span class="hljs-keyword">self</span>.addChildViewController(homeNav)
    }
</code></pre>

                    
                    </section>
                
                
                </div>
            </div>
        </div>

        
        <a href="../03/README.html" class="navigation navigation-prev " aria-label="Previous page: 纯代码搭建项目框架"><i class="fa fa-angle-left"></i></a>
        
        
        <a href="../5storyboard_reference/README.html" class="navigation navigation-next " aria-label="Next page: StoryBoard Reference"><i class="fa fa-angle-right"></i></a>
        
    </div>
</div>

        
<script src="../gitbook/app.js"></script>

    
    <script src="https://cdn.mathjax.org/mathjax/2.4-latest/MathJax.js?config=TeX-AMS-MML_HTMLorMML"></script>
    

    
    <script src="../gitbook/plugins/gitbook-plugin-mathjax/plugin.js"></script>
    

<script>
require(["gitbook"], function(gitbook) {
    var config = {"fontSettings":{"theme":null,"family":"sans","size":2}};
    gitbook.start(config);
});
</script>

        
    </body>
    
</html>
